package com.eboss2.sbs.activity;

import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.eboss2.sbs.R;
import com.eboss2.sbs.activity.base.BaseActivity;
import com.eboss2.sbs.adapter.ChooseCashAmtAdapter;
import com.eboss2.sbs.adapter.ChooseOptionAdapter;
import com.eboss2.sbs.enums.EnumConsts;
import com.eboss2.sbs.http.API;
import com.eboss2.sbs.http.HttpCallback;
import com.eboss2.sbs.model.CaculateMoneyEntity;
import com.eboss2.sbs.model.UploadResultEntity;
import com.eboss2.sbs.model.db.OrderDetail;
import com.eboss2.sbs.myapplication.MyApplication;
import com.google.gson.reflect.TypeToken;
import com.mytools.tool.activityManager.MyActivityManager;
import com.mytools.tool.utils.LocalParasUtils;
import com.mytools.tool.utils.StringUtil;
import com.mytools.tool.views.MyDialog;
import com.tool.utils.systemUtils.SystemUtils;
import com.tool.utils.utils.UtilPreference;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.BitSet;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

public class PayCashActivity extends BaseActivity implements View.OnClickListener{

	public static String CACULATE_MONEY_ENTITY = "CACULATE_MONEY_ENTITY";
	
	private static int DOT = -1;
	private static int DEL = -2;
	
	private int real_money = -1;
	
	private CaculateMoneyEntity caculateMoneyEntity;
	private String password;
	private String couponSns;
	private int pointAmount;
	
	private TextView tv_receive_money;
	private TextView tv_return_money;
	
	private int receive_money = 0;
	private int return_money = 0;
	
	private String money_str = "";
	private String orderNo;


	//支付方式
	private GridView gv_option_paytype;
	private ArrayList<String> paytype_values = new ArrayList<String>(){
		{
//			add(EnumConsts.CashType.AMOUNT_0.getName());
			add(EnumConsts.CashType.AMOUNT_5.getName());
			add(EnumConsts.CashType.AMOUNT_10.getName());
			add(EnumConsts.CashType.AMOUNT_20.getName());
			add(EnumConsts.CashType.AMOUNT_50.getName());
			add(EnumConsts.CashType.AMOUNT_100.getName());
		}
	};
	private BitSet paytype_marks = new BitSet(paytype_values.size());
	private ChooseCashAmtAdapter adapter_paytype;
	private int payType = EnumConsts.CashType.AMOUNT_0.getType();
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mContext = this;
		setContentView(R.layout.activity_pay_cash);
		MyActivityManager.getInstance().addActivity(this);

		orderNo = getIntent().getStringExtra("orderNo");
		
		password = getIntent().getStringExtra("password");
		couponSns = getIntent().getStringExtra("couponSns");
		pointAmount = getIntent().getIntExtra("pointAmount", 0);
		caculateMoneyEntity = (CaculateMoneyEntity) getIntent().getSerializableExtra(CACULATE_MONEY_ENTITY);
		if(caculateMoneyEntity==null){toast("金额参数错误");finish();return;}
		real_money = caculateMoneyEntity.getRealMoney();
		initView();
	}
	
	private void initView(){
		RelativeLayout relativeLayout = relativeLayout(R.id.lv_heard);
		relativeLayout.setBackgroundColor(getResources().getColor(R.color.statusBar));
		setTvText(R.id.tv_title, "现金记账计算器");
		
		tv_receive_money = (TextView) findViewById(R.id.tv_receive_money);
		tv_return_money = (TextView) findViewById(R.id.tv_return_money);
		
		display_money();
		
		setTvText(R.id.tv_real_money, StringUtil.getMoneyString(real_money));
		
		findViewById(R.id.titleback_btn_back).setOnClickListener(this);
		
//		findViewById(R.id.btn_money_100).setOnClickListener(this);
//		findViewById(R.id.btn_money_50).setOnClickListener(this);
//		findViewById(R.id.btn_money_20).setOnClickListener(this);
//		findViewById(R.id.btn_money_10).setOnClickListener(this);
//		findViewById(R.id.btn_money_5).setOnClickListener(this);
		
//		findViewById(R.id.tv_num_1).setOnClickListener(this);
//		findViewById(R.id.tv_num_2).setOnClickListener(this);
//		findViewById(R.id.tv_num_3).setOnClickListener(this);
//		findViewById(R.id.tv_num_4).setOnClickListener(this);
//		findViewById(R.id.tv_num_5).setOnClickListener(this);
//		findViewById(R.id.tv_num_6).setOnClickListener(this);
//		findViewById(R.id.tv_num_7).setOnClickListener(this);
//		findViewById(R.id.tv_num_8).setOnClickListener(this);
//		findViewById(R.id.tv_num_9).setOnClickListener(this);
//		findViewById(R.id.tv_num_dot).setOnClickListener(this);
//		findViewById(R.id.tv_num_0).setOnClickListener(this);
//		findViewById(R.id.tv_num_del).setOnClickListener(this);
		
		findViewById(R.id.tv_num_1).setOnClickListener(this);
		findViewById(R.id.tv_num_2).setOnClickListener(this);
		findViewById(R.id.tv_num_3).setOnClickListener(this);
		findViewById(R.id.tv_num_4).setOnClickListener(this);
		findViewById(R.id.tv_num_5).setOnClickListener(this);
		findViewById(R.id.tv_num_6).setOnClickListener(this);
		findViewById(R.id.tv_num_7).setOnClickListener(this);
		findViewById(R.id.tv_num_8).setOnClickListener(this);
		findViewById(R.id.tv_num_9).setOnClickListener(this);
		findViewById(R.id.tv_num_dot).setOnClickListener(this);
		findViewById(R.id.tv_num_0).setOnClickListener(this);
		findViewById(R.id.tv_num_del).setOnClickListener(this);
		
		findViewById(R.id.btn_submit).setOnClickListener(this);

		gv_option_paytype = (GridView) findViewById(R.id.gv_option_paytype);

		adapter_paytype = new ChooseCashAmtAdapter(mContext, paytype_values, paytype_marks);
		gv_option_paytype.setAdapter(adapter_paytype);
		gv_option_paytype.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
//				adapterNotify(TYPE_PAY_OPTION, arg2);
				payType = EnumConsts.CashType.getTypeByName(paytype_values.get(arg2));
				int size2 = paytype_values.size();
				for (int i = 0; i < size2; i++) {
					int type_tmp = EnumConsts.CashType.getTypeByName(paytype_values.get(i));
					paytype_marks.set(i, type_tmp==payType?true:false);
				}
				adapter_paytype.notifyDataSetChanged();

				if (payType == EnumConsts.CashType.AMOUNT_100.getType()){
					receive_money=10000;
					money_str="100";display_money();
				}else if (payType == EnumConsts.CashType.AMOUNT_50.getType()){
					receive_money=5000;
					money_str="50";display_money();
				}else if (payType == EnumConsts.CashType.AMOUNT_20.getType()){
					receive_money=2000;
					money_str="20";display_money();
				}else if (payType == EnumConsts.CashType.AMOUNT_10.getType()){
					receive_money=1000;
					money_str="10";display_money();
				}else if (payType == EnumConsts.CashType.AMOUNT_5.getType()){
					receive_money=500;
					money_str="5";display_money();
				}
			}
		});
		
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.titleback_btn_back:finish();break;
//			case R.id.btn_money_100:receive_money=10000;money_str="100.00";display_money();break;
//			case R.id.btn_money_50:receive_money=5000;money_str="50.00";display_money();break;
//			case R.id.btn_money_20:receive_money=2000;money_str="20.00";display_money();break;
//			case R.id.btn_money_10:receive_money=1000;money_str="10.00";display_money();break;
//			case R.id.btn_money_5:receive_money=500;money_str="5.00";display_money();break;
			
			case R.id.tv_num_1:key_event(1);break;
			case R.id.tv_num_2:key_event(2);break;
			case R.id.tv_num_3:key_event(3);break;
			case R.id.tv_num_4:key_event(4);break;
			case R.id.tv_num_5:key_event(5);break;
			case R.id.tv_num_6:key_event(6);break;
			case R.id.tv_num_7:key_event(7);break;
			case R.id.tv_num_8:key_event(8);break;
			case R.id.tv_num_9:key_event(9);break;
			case R.id.tv_num_dot:key_event(DOT);break;
			case R.id.tv_num_0:key_event(0);break;
			case R.id.tv_num_del:key_event(DEL);break;
	
			case R.id.btn_submit:doSubmit_pre();break;
			default: break;
		}
	}
	
	private void key_event(int key){

		int size2 = paytype_values.size();
		for (int i = 0; i < size2; i++) {
			paytype_marks.set(i, false);
		}
		adapter_paytype.notifyDataSetChanged();


		if(key>=0&&key<=9){
			if(Pattern.compile("\\d+\\.\\d{2}").matcher(money_str).matches()){return;}
			if(money_str.replaceAll("\\..*", "").length()>7){return;}
			money_str = money_str + key;
			float tmp = Float.parseFloat(money_str);
			receive_money = (int) (tmp*100);
			display_money();
		}
		else if(key==DOT){
			if(Pattern.compile(".*\\..*").matcher(money_str).matches()){return;}
			if(money_str.length()>=8){return;}
			if(StringUtil.isNull(money_str)){money_str = "0.";receive_money=0;}
			else money_str = money_str + ".";
			display_money();
		}
		else if(key==DEL){
			if(StringUtil.isNull(money_str)){return;}
			money_str = money_str.substring(0, money_str.length()-1);
			if(StringUtil.isNull(money_str)){money_str = "";receive_money = 0;}
			else{
				float tmp = Float.parseFloat(money_str);
				receive_money = (int) (tmp*100);
			}
			display_money();
		}
	}
	
	private void display_money(){
		tv_receive_money.setText(money_str);
		if(receive_money<=real_money){return_money=0;}
		else{return_money = receive_money-real_money;}
		tv_return_money.setText(StringUtil.getMoneyString(return_money));
	}
	
	private void doSubmit_pre(){
		MyDialog dialog;
		MyDialog.Builder builder = new MyDialog.Builder(this);
		builder.setTitle("提示");
		builder.setMessage("确认已经收到现金 "+StringUtil.getMoneyString(real_money)+" 元");
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				doSubmit();
			}
		});
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int arg1) {
				dialog.dismiss();
			}
		});
//		builder.create().setCancelable(false);
//		builder.create().show();
		dialog=builder.create();
//		dialog.setCancelable(false);
		dialog.show();
	}

//	@Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
//	public void getOrderNo(String event){
//		orderNo = event;
//	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		//取消注册 , 防止Activity内存泄漏
//		EventBus.getDefault().unregister( this ) ;
	}


	private void doSubmit(){

//		EventBus.getDefault().register(this);
		long t = new Date().getTime();
		
		saveLocalTradeDetail(t, orderNo);
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("sid", MyApplication.getmInstance().getLoginMEntity().getShopid());
		String memberCardNo = caculateMoneyEntity.getMemberCardNo();
		if(!StringUtil.isNull(memberCardNo)){params.put("cardNo", memberCardNo);}
		else{params.put("cardNo", "");}
		if(!StringUtil.isNull(password)){params.put("password", password);}
		else{params.put("password", "");}
		if(!StringUtil.isNull(couponSns)){params.put("couponSns", couponSns);}
		else{params.put("couponSns", "");}
		
		params.put("cash", caculateMoneyEntity.getRealMoney());
		params.put("bankAmount", "");
		params.put("couponCoverAmount", caculateMoneyEntity.getCouponCoverMoney());
		params.put("pointCoverAmount", caculateMoneyEntity.getPointCoverMoney());
		params.put("clientOrderNo", orderNo);

		params.put("activateCode",UtilPreference.getStringValue(mContext, "tid"));
		params.put("merchantNo", UtilPreference.getStringValue(mContext, "mid"));
		params.put("scanOrganization", UtilPreference.getIntValue(mContext, "scanOrganization", 0));

		params.put("t", t);
		params.put("transNo", "");
		params.put("authCode", "");
		params.put("pointAmount", pointAmount);
		params.put("serialNum", SystemUtils.getIMEI(mContext));
		params.put("payType", EnumConsts.SqbPayChannel.CASH_MEMO.getType());
		params.put("operator_num", "01");

		API.http_post(this, API.TRADE_LOG_UPLOAD, params, new HttpCallback<UploadResultEntity>(this) {
			@Override
			public void onSuccess(int statusCode, UploadResultEntity data) {
				updateOrderDetail(orderNo, data);
				openConfirmDialog();
			}

			@Override
			public void onFailure(int statusCode, String message) {
				openConfirmDialog();
				super.onFailure(statusCode, message);
			}
			
			@SuppressWarnings({ "unchecked", "rawtypes" })
			@Override
			public TypeToken getTypeToken() {
				return new TypeToken<UploadResultEntity>() {
				};
			}
		});
		
	}
	
	private void updateOrderDetail(String clientOrderNo, UploadResultEntity data) {
		ContentValues cv = new ContentValues();
		String point_url = data.getPoint_url();
//		String coupon_url = data.getCoupon();
		cv.put("point_url", StringUtil.isNull(point_url)?"":point_url);
//		cv.put("coupon_url", StringUtil.isNull(coupon_url)?"":coupon_url);
		int point = data.getPoint();
		int pointCurrent = data.getPointCurrent();
		cv.put("point", point);
		cv.put("pointCurrent", pointCurrent);
		
		DataSupport.updateAll(OrderDetail.class, cv, "tradeOrderNo = ?", clientOrderNo);
	}
	
	private void saveLocalTradeDetail(long t, String tradeOrderNo){
		OrderDetail orderDetail = new OrderDetail();
		orderDetail.setSid(MyApplication.getmInstance().getLoginMEntity().getShopid());
		orderDetail.setTradeOrderNo(tradeOrderNo);
		orderDetail.setPayType(EnumConsts.SqbPayChannel.CASH_MEMO.getType());
		orderDetail.setTerminalSn(""+LocalParasUtils.getMerchantNo(this));
		orderDetail.setState(EnumConsts.SqbPayState.SUCCESS.getType());
		orderDetail.setTradeMoney(caculateMoneyEntity.getTradeMoney());
		orderDetail.setRealMoney(caculateMoneyEntity.getRealMoney());
		orderDetail.setMemberName(caculateMoneyEntity.getMemberName());
		
		int couponCoverMoney = caculateMoneyEntity.getCouponCoverMoney();
		int pointCoverMoney = caculateMoneyEntity.getPointCoverMoney();
		String couponString = couponCoverMoney==0?"":("优惠券抵消"+StringUtil.getMoneyString(couponCoverMoney)+"元;");
		String pointString = pointCoverMoney==0?"":("积分抵消"+StringUtil.getMoneyString(pointCoverMoney)+"元;");
		if(!StringUtil.isNull(couponString)||!StringUtil.isNull(pointString)) orderDetail.setBenefit(pointString+couponString);
		
		orderDetail.setTradeTime(t);
		if(!StringUtil.isNull(password)){orderDetail.setPassword(password);}
		if(!StringUtil.isNull(couponSns)){orderDetail.setCouponSns(couponSns);}
		String memberCardNo = caculateMoneyEntity.getMemberCardNo();
		if(!StringUtil.isNull(memberCardNo)){orderDetail.setCardNo(memberCardNo);}
		orderDetail.setPointAmount(pointAmount);
		orderDetail.setCash(caculateMoneyEntity.getRealMoney());
		orderDetail.setBankAmount(0);


		orderDetail.setTerminalSn(UtilPreference.getStringValue(mContext, "mid"));
		orderDetail.setMerchantNo(UtilPreference.getStringValue(mContext, "mid"));
		orderDetail.setActivateCode(UtilPreference.getStringValue(mContext, "tid"));
		orderDetail.setTerminalName(UtilPreference.getStringValue(mContext, "merchantName"));

		orderDetail.setSerialNum(SystemUtils.getIMEI(mContext));
		orderDetail.save();
	}
	
	private void openConfirmDialog(){
		MyDialog.Builder builder = new MyDialog.Builder(this);
		builder.setTitle("提示");
		builder.setMessage("现金收款成功！");
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				finish();
				startActivity(new Intent(mContext, PayMoneyInputActivity.class));
				
				Intent intent = new Intent(PayMoneyInputActivity.RECEIVER_CLEAN_DATA_TAG);
				intent.putExtra(PayMoneyInputActivity.NOTIFY_CODE_TAG, PayMoneyInputActivity.CLEAN_DATA);
		        sendBroadcast(intent);
		        
			}
		});
		builder.create().show();
	}
	
}
